package triannon.client.util.timer;

import java.util.ArrayList;

import javax.swing.SwingUtilities;

public class TTimer extends Thread {
	private long lastUpdate;
	private ArrayList<TTimerListener> listeners = new ArrayList<TTimerListener>();
	private static TTimer instance = null;
	private long updateEveryMs = 0;
	private boolean running = false;

	private TTimer() {
	}

	public static TTimer getInstance() {
		if (instance == null) {
			instance = new TTimer();
		}

		return instance;
	}

	public void startTimer(long fps) {
		this.updateEveryMs = 1000L / fps;

		lastUpdate = System.currentTimeMillis();
		if (!running) {
			running = true;
			start();
		}
	}

	public void addSTimerListener(TTimerListener listener) {
		synchronized (listeners) {
			listeners.add(listener);
		}
	}

	public void removeSTimerListener(TTimerListener listener) {
		synchronized (listeners) {
			listeners.remove(listener);
		}
	}

	@Override
	public void run() {
		while (running) {

			try {
				sleep(updateEveryMs);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			final long tpf = System.currentTimeMillis() - lastUpdate;
			lastUpdate = System.currentTimeMillis();

			synchronized (listeners) {
				for (final TTimerListener listener : listeners) {
					SwingUtilities.invokeLater(new Runnable() {

						@Override
						public void run() {
							listener.update(tpf);

						}
					});
				}
			}
		}
	}
}
